package com.ruoyi.web.controller.common;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.client.StockClient;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.vo.StockResponse;
import com.ruoyi.common.vo.StockVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 获取股票
 * 
 * @author zhangcunlei
 */
@RestController
@RequestMapping("/stock")
public class StockController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(StockController.class);

    @Resource
    private StockClient stockClient;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取股票基础信息
     * 
     */
    @GetMapping("/getStock")
    public AjaxResult getStock(@RequestParam String code) {
        log.info("获取股票基础信息，code:{}", code);
        if (StringUtils.isBlank(code)) {
            return success();
        }
        // 暂时放入中间件10分钟
        String stockKey = CacheConstants.STOCK_KEY + code;
        String stockValue = redisCache.getCacheObject(stockKey);
        List<StockVO> stockRespList = new ArrayList<>();
        if (StringUtils.isBlank(stockValue)) {
            StockResponse stockResponse = stockClient.getStock(code);
            stockRespList.addAll(stockResponse.getData());
            redisCache.setCacheObject(stockKey, JSON.toJSONString(stockResponse.getData()), 10, TimeUnit.MINUTES);
        } else {
            stockRespList.addAll(JSONArray.parseArray(stockValue, StockVO.class));
        }
        return success(stockRespList);
    }

}
